/*
 * Copyright 2007 Brian Watkins
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package bw.util;

import java.util.*;

public class WorkerPool
{
    protected String _name = null;
    protected ArrayList _workers = new ArrayList();
    protected int _workerIndex = 0;

    //maintains a pool of Worker threads. Hands work to one work at a time
    //in a round-robin fashion. Accepts an endless amount of work. 

    public WorkerPool ( String name, int size )
    {
        _name = name;

        for ( int i = 0; i < size; i++ )
        {
            Worker worker = new Worker( _name + "_" + i );
            worker.start();
            _workers.add( worker );
        }
    }

    protected Worker getAvailableWorker ()
    {
        Worker worker = null;
        
        synchronized ( _workers )
        {
            //assuming _workers has size > 0
            worker = (Worker) _workers.get( _workerIndex++ );
        
            if ( _workerIndex == _workers.size() )
            {
                _workerIndex = 0;
            }
        }

        return worker;
    }

    public void addWork ( Runnable work )
    {
        Worker worker = getAvailableWorker();
        if ( worker != null )
        {
            worker.addWork( work );
        }
    }

    public void shutdown ()
    {
        Iterator workers = _workers.iterator();
        while ( workers.hasNext() )
        {
            Worker worker = (Worker) workers.next();
            worker.shutdown();
        }
    }
}